
import http from '@ohos.net.http';
import hilog from '@ohos.hilog';
export class ALiYunHttpUtils {

  request(question: string,callback:(text:string)=>void) {
    hilog.info(0x0000, 'testTag', 'ALiYunHttpUtils request invoke. question: %{public}s', question);

    // 1 createHttp接口创建请求
    let httpRequest = http.createHttp();

    // 2 发起请求
    httpRequest.request(
      // 请求地址
      "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
      // 请求options: HttpRequestOptions
      {
        // 请求方式
        method: http.RequestMethod.POST,
        // 请求头
        header: {
          "Content-Type": "application/json",
          // 这里的Authorization 就是刚才工作台查看的 API-KEY
          "Authorization": "sk-5323a0035d9740e38e51c85e4410325a" // 脱敏处理
        },
        // 请求体
        extraData: {
          "model": "qwen-plus", // 指定用于对话的通义千问模型名
          "input": {
            "messages": [
              {
                "role": "user",
                "content": question // 请求发起方传入的问题
              }
            ]
          }
        }
      }, (err, data: http.HttpResponse) => {
      if (err) {
        hilog.error(0x0000, 'testTag', 'Failed to request ALiYun. Cause: %{public}s', JSON.stringify(err) ?? '');
        httpRequest.destroy();
      } else {
        // hilog.error(0x0000, 'testTag', 'Request ALiYun success. data: %{public}s', JSON.stringify(data.result));
        try {
          // 关键解析步骤
          const response = JSON.parse(data.result as string); // 先解析外层字符串
          const targetText = response.output.text; // 直接访问目标路径

          hilog.info(0x0000, 'testTag', '提取到的文本: %{public}s', targetText);
          callback(targetText);
        } catch (e) {
          hilog.error(0x0000, 'testTag', '解析失败: %{public}s', e.message);
        }
        httpRequest.destroy();
      }
    })
  }

}
export const aliYunHttpUtils = new ALiYunHttpUtils();